const { catesModel } = require('../../models/goods')

module.exports = class Cate {
  // 获取商品分类
  static async getCates(ctx) {
    // 查询数据库
    let data = await catesModel.find({pid:0}, { __v: 0 })
    let arr = JSON.parse(JSON.stringify(data))

    // 获取子级分类数据
    for (let i = 0; i < arr.length; i++) {
      let data2 = await catesModel.find({ pid: arr[i]._id })
      let arr2 = JSON.parse(JSON.stringify(data2));

      for (let j = 0; j < arr2.length; j++){
        let data3 = await catesModel.find({ pid: arr2[j]._id })
        arr2[j]['children'] = data3;
      }

      arr[i]['children'] = arr2;
    }


    ctx.body = {
      code: 200,
      msg: '获取成功',
      data: arr
    }

  }

  // 设置商品分类
  static async addCates(ctx) {
    // console.log(ctx.request.body);
    let { pid, name_en, name_zh, imgUrl = "" } = ctx.request.body;

    let state = false;
    if (pid && name_en && name_zh) state = true;

    if (state) {
      let data = await catesModel.insertMany({ pid, name_en, name_zh, imgUrl })
      data.length ? end(ctx, 200, '添加成功', data) : end(ctx, 400, '添加失败')
    } else {
      end(ctx, 300, '有未填字段')
    }
  }
}